//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package api_coll_dao

import (
	"context"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/http_custom_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type ApiGroupInfoDbItem struct {
	GroupId   string `bson:"_id"`
	ApiCollId string `bson:"apiCollId"`
	GroupName string `bson:"groupName"`
	ItemCount uint32 `bson:"itemCount"`
	TimeStamp int64  `bson:"timeStamp"`
}

func (item *ApiGroupInfoDbItem) ToApiGroupInfo() *http_custom_api.ApiGroupInfo {
	return &http_custom_api.ApiGroupInfo{
		GroupId:   item.GroupId,
		GroupName: item.GroupName,
		ItemCount: item.ItemCount,
	}
}

type _ApiGroupDao struct {
	mc *mongo.Collection
}

func newApiGroupDao(db *mongo.Database) (*_ApiGroupDao, error) {
	mc := db.Collection(db_ns.DB_NS_API_COLLECTION + "custom_group")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"apiCollId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_ApiGroupDao{mc: mc}, nil
}

func (db *_ApiGroupDao) Insert(ctx context.Context, dbItem *ApiGroupInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ApiGroupDao) List(ctx context.Context, apiCollId string) ([]*ApiGroupInfoDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"apiCollId": apiCollId}, options.Find().SetSort(bson.M{"groupName": 1}))
	if err != nil {
		return nil, err
	}
	retList := []*ApiGroupInfoDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_ApiGroupDao) Get(ctx context.Context, apiCollId, groupId string) (*ApiGroupInfoDbItem, error) {
	retItem := &ApiGroupInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"apiCollId": apiCollId, "_id": groupId}).Decode(retItem)
	return retItem, err
}

func (db *_ApiGroupDao) Exist(ctx context.Context, apiCollId, groupId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"apiCollId": apiCollId, "_id": groupId})
	return count > 0, err
}

func (db *_ApiGroupDao) Remove(ctx context.Context, apiCollId, groupId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"apiCollId": apiCollId, "_id": groupId})
	return err
}

func (db *_ApiGroupDao) RemoveByColl(ctx context.Context, apiCollId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"apiCollId": apiCollId})
	return err
}

func (db *_ApiGroupDao) Update(ctx context.Context, apiCollId, groupId, groupName string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"apiCollId": apiCollId, "_id": groupId}, bson.M{"$set": bson.M{"groupName": groupName}})
	return err
}

func (db *_ApiGroupDao) UpdateItemCount(ctx context.Context, apiCollId, groupId string, itemCount uint32) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"apiCollId": apiCollId, "_id": groupId}, bson.M{"$set": bson.M{"itemCount": itemCount}})
	return err
}
